package com.zhangsr.zus.config.spring;

import com.zhangsr.zus.config.api.ZusServiceConfig;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.support.AbstractApplicationContext;

import java.lang.reflect.Method;

/**
 * @Author: zhangsr
 */
public class ServiceBean<T> extends ZusServiceConfig<T>
        implements InitializingBean, DisposableBean, ApplicationContextAware, ApplicationListener, BeanNameAware {

    private static final Logger logger = Logger.getLogger(ServiceBean.class);

    private static transient ApplicationContext SPRING_CONTEXT;

    private transient ApplicationContext applicationContext;
    private transient String beanName;

    private transient boolean supportedApplicationListener;


    /**
     * 通过 ApplicationContextAware 获取 ApplicationContext 实例
     * <p/>
     * Using implements ApplicationContextAware
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        if (applicationContext != null) {
            SPRING_CONTEXT = applicationContext;
            try {
                Method method = applicationContext.getClass().getMethod("addApplicationListener", new Class<?>[]{ApplicationListener.class}); // 兼容Spring2.0.1
                method.invoke(applicationContext, new Object[]{this});
                supportedApplicationListener = true;
            } catch (Throwable t) {
                if (applicationContext instanceof AbstractApplicationContext) {
                    try {
                        Method method = AbstractApplicationContext.class.getDeclaredMethod("addListener", new Class<?>[]{ApplicationListener.class}); // 兼容Spring2.0.1
                        if (!method.isAccessible()) {
                            method.setAccessible(true);
                        }
                        method.invoke(applicationContext, new Object[]{this});
                        supportedApplicationListener = true;
                    } catch (Throwable t2) {
                    }
                }
            }
        }
    }

    public void setBeanName(String name) {
        this.beanName = name;
    }

    /**
     * 通过 ApplicationListener 监听自定义事件
     * <p/>
     * Using implements ApplicationListener
     */
    public void onApplicationEvent(ApplicationEvent event) {
        if (ContextRefreshedEvent.class.getName().equals(event.getClass().getName())) {
            if (isExported()) {
                this.logger.info("ZUS have running on server..");
                return;
            }
            this.logger.info("ZUS begin to startup by applicationEvent.");
            export();
        }
    }

    /**
     * Using implements InitializingBean
     */
    public void afterPropertiesSet() throws Exception {
        if (isExported()) {
            this.logger.info("ZUS have running on server..");
            return;
        }
        logger.info("ZUS begin to startup by afterPropertiesSet.");
        export();
    }

    public void destroy() throws Exception {
        unexport();
    }

}
